//
//  BanBu_ManuscriptTableViewCell.m
// Halfarea
//
//  Created by banbu3 on 14/6/4.
//
//

#import "BanBu_ManuscriptTableViewCell.h"
#import "BanBuAPIs.h"
#import "AppCommunicationManager.h"
#import "AppDataManager.h"
#import "BanBu_ImageView.h"
#import "BanBu_ThemeManager.h"
#import "BanBu_ManuscriptAPI.h"
#import "BanBu_SmileViewAPI.h"

#define MaxCollectWidth 220

@implementation BanBu_ManuscriptTableViewCell

//设置背景颜色
-(void)setBg
{
    BanBu_ImageView *backImage = [[BanBu_ImageView alloc] initWithBackGroundImageType:UIImageViewCreatTypeCell];
    backImage.frame = CGRectMake(0, 0, 320, self.bounds.size.height);
    self.backgroundView = backImage;
    [backImage release];
    
    lineView = [[UIImageView alloc] initWithFrame:CGRectMake(-40, self.bounds.size.height-1, 360, 1.0)];
    lineView.image = [ThemeManager getThemeImage:@"lineColor.png"];
    [self.contentView addSubview:lineView];
    [lineView release];
    
    _mediaView = [_mediaView initWithFrame:_mediaView.frame];
    _voiceView = [_voiceView initWithFrame:_voiceView.frame];
}
- (void)awakeFromNib
{
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

//设置cell的各属性
-(void)setCellInfo:(NSDictionary *)infoDic withEditing:(BOOL)editing 
{
    [m_checkImageView setHidden:!editing];
    
    self.collectedDic = infoDic;
    [self setAvactorImage:[infoDic valueForKey:KeyUface]];
    [self setName:[infoDic valueForKey:KeyPname]];
    [self setMsgTime:[infoDic valueForKey:KeyCollectAmsgTime]];
    
    [self setCollectedType:[[infoDic valueForKey:KeyType] integerValue]];
}

//设置头像
- (void)setAvactorImage:(NSString *)imageStr
{
    _avactor.layer.cornerRadius = 20.0f;
    _avactor.layer.masksToBounds = YES;
    [_avactor setImageWithURL:[NSURL URLWithString:imageStr] placeholderImage:[UIImage imageNamed:@"default.png"] andType:1];
}

//设置昵称
- (void)setName:(NSString *)name
{
    _nameLabel.text = name;
}

//设置消息时间
-(void)setMsgTime:(NSString *)time
{
    _timeLabel.hidden = NO;

    if (time.length>15)
    {
//        _timeLabel.text = [time substringWithRange:NSMakeRange(5, [time length]-5-3)];
        _timeLabel.text = [time substringWithRange:NSMakeRange(0, 10)];
    }
    else
    {
        _timeLabel.text = time;
    }
    
}

//设置收藏的消息类型
-(void)setCollectedType:(MsgType)type
{
    self.activitIndicator.hidden = YES;
    [self.activitIndicator stopAnimating];
    _voiceBg.hidden = YES;
    _type = type;
    switch (type)
    {
        case MsgTypeText:
        {
            _smileLabel.hidden = NO;
            _mediaView.hidden = YES;
            _voiceView.hidden = YES;
            [self setSmileLabelText:[_collectedDic valueForKey:KeyContent]];
        }
            break;
        case MsgTypeImage:
        {
            _smileLabel.hidden = YES;
            _mediaView.hidden = NO;
            _voiceView.hidden = YES;
            [self setMediaViewImage:[_collectedDic valueForKey:KeyContent]];
        }
            break;
        case MsgTypeVoice:
        {
            _smileLabel.hidden = YES;
            _mediaView.hidden = YES;
            _voiceView.hidden = NO;
            [self setVoiceViewData:[_collectedDic valueForKey:KeyContent]];
        }
            break;
        default:
        {
            _smileLabel.hidden = NO;
            _mediaView.hidden = YES;
            _voiceView.hidden = YES;
            [self setSmileLabelText:[_collectedDic valueForKey:KeyContent]];
        }
            break;
    }
    
    NSString * content = [AppComManager pathForCollectImage:[_collectedDic valueForKey:KeyContent]];
    if (![FileManager fileExistsAtPath:content])
    {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(stopLoading) name:KFinishdownloadingAmsgFile object:nil];
    }
}

//设置文本型消息的内容
- (void)setSmileLabelText:(NSString *)text
{
    self.smileLabel.text = text;
    
    CGSize size =  [self.smileLabel.text sizeWithFont:DefaultFont constrainedToSize:CGSizeMake(MaxWidth-20, 1000)lineBreakMode:kTextLineBreakByWordWrapping];
    if (size.width<23)
    {
        size.width = 23;
    }
    
    CGRect newFrame = self.smileLabel.frame;
    newFrame.size.height = size.height + ((size.height>20 )?20:0);
    if (newFrame.size.height>60)
    {
        newFrame.size.height = 60;
    }
    newFrame.size.width = (size.height>DefaultHeight)?MaxWidth:(size.width + 20);
    
    self.smileLabel.frame = newFrame;
    self.bkViewWidth = self.smileLabel.frame.size.width;
    
    if(self.smileLabel.frame.size.height>60)
    {
        self.bkViewWidth = 220;
    }
}

//设置图片
-(void)setMediaViewImage:(NSString *)imageUrl
{
    self.bkViewWidth = 90.0;
    
    MediaStatus status = MediaStatusNormal;
    NSString *content = imageUrl;
    
    _mediaView.snapMsg = NO;
    
    //如果没下载图片，则开线程去下载
    content = [AppComManager pathForCollectImage:content];
    if (![FileManager fileExistsAtPath:content])
    {
        [AppComManager downloadAmsgFileWithUrl:imageUrl withUserId:MyAppDataManager.useruid withFolder:ManuscriptFolder withDelegate:self];
        self.activitIndicator.hidden = NO;
        [self.activitIndicator startAnimating];
    }
    else
    {
        self.activitIndicator.hidden = YES;
        [_mediaView setMedia:imageUrl withFrom:@"collectimage"];
        [_mediaView setStatus:status];
    }
}

/**
 *	@brief	设置语音
 *
 *	@param 	voiceUrl 	语音路径
 */
-(void)setVoiceViewData:(NSString *)voiceUrl
{
    self.bkViewWidth = 80.0;
    _voiceBg.hidden = NO;
    
    _voiceBg.image = [_voiceBg.image stretchableImageWithLeftCapWidth:31.0 topCapHeight:25.0];
    
    MediaStatus status = MediaStatusNormal;
    NSString *content = voiceUrl;
    
    [_voiceView setStatus:status];
    [_voiceView setMedia:content];
    _voiceView.from = @"collectvoice";
    
    _voiceView.isLeft = YES;
    
    //如果没下载图片，则开线程去下载
    content = [AppComManager pathForCollectImage:content];
    if (![FileManager fileExistsAtPath:content])
    {
        [AppComManager downloadAmsgFileWithUrl:voiceUrl withUserId:MyAppDataManager.useruid withFolder:ManuscriptFolder withDelegate:self];
        self.activitIndicator.hidden = NO;
        
        [self.activitIndicator startAnimating];
    }
    else
    {
        self.activitIndicator.hidden = YES;

        NSData *data=[NSData dataWithContentsOfFile:content];
        
        if(data)
        {
            AVAudioPlayer *player=[[AVAudioPlayer alloc]initWithData:data error:nil];
            
            [self setVoiceViewLong:player.duration];
            [player release];
        }
    }
}

-(void)stopLoading
{
    NSString *content = [_collectedDic valueForKey:KeyContent];
    content = [AppComManager pathForCollectImage:content];
    if ([FileManager fileExistsAtPath:content])
    {
        self.activitIndicator.hidden = YES;
        
        [self.activitIndicator stopAnimating];
        
        [self setCollectedType:_type];
    }
}

//设置语音气泡的长度
-(void)setVoiceViewLong:(CGFloat)time
{
    [_voiceView setTime:time];
    self.bkViewWidth = 160.0;
}


#pragma mark - 设置选中状态
//编辑状态
- (void) setEditing:(BOOL)editting animated:(BOOL)animated
{
	if (self.editing == editting)
	{
		return;
	}
    
	[super setEditing:editting animated:animated];
	
	if (editting)
	{
		self.selectionStyle = UITableViewCellSelectionStyleNone;
		self.textLabel.backgroundColor = [UIColor clearColor];
		self.detailTextLabel.backgroundColor = [UIColor clearColor];
		[_nameLabel setFrame:CGRectMake(60, 7, 140, 19)];
        [_timeLabel setFrame:CGRectMake(190, 7, 100, 19)];
        [_smileLabel setFrame:CGRectMake(60, 27, 220, 60)];
        [_voiceView setFrame:CGRectMake(70, 46, 155, 40)];
        [_voiceBg setFrame:CGRectMake(60, 31, 180, 50)];
		if (m_checkImageView == nil)
		{
			m_checkImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"CellNotSelected.png"]];
			[self addSubview:m_checkImageView];
		}
        [m_checkImageView setHidden:NO];
		[self setChecked:m_checked];
 		m_checkImageView.center = CGPointMake(-CGRectGetWidth(m_checkImageView.frame) * 0.5,
											  CGRectGetHeight(self.bounds) * 0.5);
		m_checkImageView.alpha = 0.0;
		[self setCheckImageViewCenter:CGPointMake(20.5, CGRectGetHeight(self.bounds) * 0.5)
								alpha:1.0 animated:animated];
        
        self.mediaView.userInteractionEnabled = NO;
        self.voiceView.userInteractionEnabled = NO;
	}
	else
	{
        [_voiceBg setFrame:CGRectMake(80, 31, 180, 50)];
        [_voiceView setFrame:CGRectMake(90, 46, 155, 40)];
        [_smileLabel setFrame:CGRectMake(80, 27, 220, 60)];
        [_nameLabel setFrame:CGRectMake(80, 7, 140, 19)];
        [_timeLabel setFrame:CGRectMake(220, 7, 100, 19)];
		m_checked = NO;
		self.selectionStyle = UITableViewCellSelectionStyleBlue;
		
		if (m_checkImageView)
		{
			[self setCheckImageViewCenter:CGPointMake(-CGRectGetWidth(m_checkImageView.frame) * 0.5,
													  CGRectGetHeight(self.bounds) * 0.5)
									alpha:0.0
								 animated:animated];
            [m_checkImageView setHidden:YES];
		}
        self.mediaView.userInteractionEnabled = YES;
        self.voiceView.userInteractionEnabled = YES;
	}
}

//多选删除部分
- (void) setCheckImageViewCenter:(CGPoint)pt alpha:(CGFloat)alpha animated:(BOOL)animated
{
	if (animated)
	{
		[UIView beginAnimations:nil context:nil];
		[UIView setAnimationBeginsFromCurrentState:YES];
		[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
		[UIView setAnimationDuration:0.3];
		
		m_checkImageView.center = pt;
		m_checkImageView.alpha = alpha;
		
		[UIView commitAnimations];
	}
	else
	{
		m_checkImageView.center = pt;
		m_checkImageView.alpha = alpha;
	}
}


- (void)setChecked:(BOOL)checked
{
	if (checked)
	{
		m_checkImageView.image = [UIImage imageNamed:@"CellSelected.png"];
 	}
	else
	{
		m_checkImageView.image = [UIImage imageNamed:@"CellNotSelected.png"];
 	}
	m_checked = checked;
}

- (void)dealloc
{
    [_collectedDic release];
    [_avactor release];
    [_nameLabel release];
    [_timeLabel release];
    [_smileLabel release];
    [_mediaView release];
    [_voiceView release];
    [_inputText release];
    [_activitIndicator release];
    [_voiceBg release];
    [super dealloc];
}

- (void)banbuDownloadRequest:(NSDictionary *)resDic didFinishedWithError:(NSError *)error
{
    if ([[resDic valueForKey:@"ok"] boolValue])
    {
        [self setCollectedType:_type];
    }
}

#pragma mark -
/**
 * @函数名称：layoutSubviews
 * @函数描述：滑动cell时改变位置，主要为了解决点删除再点取消cell错位问题
 * @输入参数：
 * @输出参数：
 * @返回值：
 * @author：yinlinlin
 */
- (void)layoutSubviews
{
    lineView.image = [ThemeManager getThemeImage:@"lineColor.png"];
    [super layoutSubviews];
    
    if (!self.editing)
    {
        //by yinlinlin 2014年08月12日16:23:51,选中删除的对话时，移动table，点击完成，有两个cell位置不正确，修改
        [_voiceBg setFrame:CGRectMake(80, 31, 180, 50)];
        [_voiceView setFrame:CGRectMake(90, 46, 155, 40)];
        [_smileLabel setFrame:CGRectMake(80, 27, 220, 60)];
        [_nameLabel setFrame:CGRectMake(80, 7, 140, 19)];
        [_timeLabel setFrame:CGRectMake(220, 7, 100, 19)];
		m_checked = NO;
		self.selectionStyle = UITableViewCellSelectionStyleBlue;
		
		if (m_checkImageView)
		{
			[self setCheckImageViewCenter:CGPointMake(-CGRectGetWidth(m_checkImageView.frame) * 0.5,
													  CGRectGetHeight(self.bounds) * 0.5)
									alpha:0.0
								 animated:NO];
            [m_checkImageView setHidden:YES];
		}
        self.mediaView.userInteractionEnabled = YES;
        self.voiceView.userInteractionEnabled = YES;
	}
    
}
@end
